package Controlor;

import Model.DAO.UserDao;
import Model.Entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/RegisterCheck")
public class CheckRegister extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //验证码校验
        String text = req.getSession().getAttribute("text").toString();
        String code = req.getParameter("image");
        //密码重复校验

        String pwd = req.getParameter("pwd");
        String pwd2 = req.getParameter("pwd2");
        //重复账号校验
        UserDao userDao = new UserDao();
        User user = new User();
        user.setName(req.getParameter("name"));
        user.setPassword(pwd);
        if(code.equals(text)){
            if (pwd.equals(pwd2)){
                if(userDao.searchUser(user)==0){
                    req.getSession().setAttribute("username",user.getName());
                    req.removeAttribute("error");
                    userDao.insertUser(user);
                    req.getRequestDispatcher("/index.jsp").forward(req,resp);
                }else {
                    popAlert(resp,"已存在该账号！");
                }
            }
            else {
                popAlert(resp,"两次输入密码不一致！");
            }
        }
        else {
            popAlert(resp,"验证码错误！");
        }
    }
    public void popAlert(HttpServletResponse response,String error) {
        response.setCharacterEncoding("utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        out.print("<script>alert('"+error+".'); window.location='register.jsp' </script>");
        out.flush();
        out.close();

    }
}
